import { deleteUser, queryUserList } from "@/api/system/user";
import { User } from "@/types/system/user";
import { deleteFileInf } from "@/utils/deleteFileInf";
import { message } from "antd";
import { useState, useCallback, useEffect } from "react";

export const useUserTable = ()=>{
    const [messageApi] = message.useMessage();
    const [loading, setLoading] = useState(false);
    const [searchForm, setSearchForm] = useState<User.Query>({
      userName: '',
      nickName: '',
      email: '',
      phonenumber: '',
      sex: '',
      type: '',
      // 账号状态（0正常 1停用
      status: '',
    });
    const [pagination, setPagination] = useState<Pagination>({
      pageNo: 1,
      pageSize: 10,
      total: 0,
    });
    const [tableData, setTableData] = useState<User.Row[]>([]);
    /**
     * 获取标签列表
     */
    const getUserList = useCallback(async () => {
      setLoading(true);
      const params = {
        pageNo: pagination.pageNo,
        pageSize: pagination.pageSize,
        ...searchForm,
      };
      const res = await queryUserList(params);
      setLoading(false);
      if (res.code === 200) {
        setTableData(res.data.rows || []);
        setPagination({
          pageNo: pagination.pageNo,
          pageSize: pagination.pageSize,
          total: res.data.total,
        });
      }
    }, [pagination.pageNo, pagination.pageSize, searchForm]);
    /**
     * 删除用户
     * @param id 
     */
    const removeUser = async (row: User.Row) => {
        const res = await deleteUser({
            ids: [row.id]
        })
        if (res.code == 200) {
            messageApi.success('删除成功!')
            row.avatar && deleteFileInf(row.avatar)
            if (tableData.length === 1) {
                setPagination({
                    pageNo: Math.max(1, pagination.pageNo - 1),
                    pageSize: pagination.pageSize,
                    total: pagination.total
                })
            } else {
                getUserList()
            }
        }
    }
    useEffect(() => {
      getUserList();
    }, [getUserList, searchForm]);
    return {
        tableData,
        loading,
        pagination,
        removeUser,
        setPagination,
        setSearchForm,
        getUserList
    }
}